package curl;

import com.fasterxml.jackson.databind.ObjectMapper;
import jdbc.SQLTemplate;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.sql.SQLException;
import java.util.*;

/**
 * Created by Administrator on 2017/11/24.
 */
public class Curl {
    public static void get(String url,Map<String,String> paramMap){
        HttpGet httpGet = null;
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(url+"?");
        if (paramMap!=null){
            Iterator iterator = paramMap.keySet().iterator();
            while (iterator.hasNext()){
                String key = (String) iterator.next();
                String value = paramMap.get(key);
                stringBuilder.append(key+"="+value+"&");
            }
            String finalurl = stringBuilder.toString().substring(0,stringBuilder.toString().length()-1);
            System.out.println(finalurl);
             httpGet = new HttpGet(finalurl);
        }else{
             httpGet = new HttpGet(url);
        }
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity!=null){
                System.out.println("响应状态  "+response.getStatusLine());
                String content = EntityUtils.toString(responseEntity,"UTF-8"); // 响应数据，存入数据库
                ObjectMapper objectMapper = new ObjectMapper();
                if (content.contains("error")){
                    Map<String,String> dataMap = objectMapper.readValue(content,Map.class);
                    System.err.println("Error-"+dataMap.get("error")+new Date().toString());
                    System.err.println("睡眠10s");
                    try {
                        Thread.sleep((1000*10));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else if(content.contains("aqi")){ // 存入数据库
                    System.out.println(content.substring(0,50)+"   "+new Date().toString());
                    try {
                        SQLTemplate.addSQL(content,"成功","pm25"); // 原始数据
                        System.err.println("倒计时");
                        int i = 55;
                        while (i>0){
                            System.err.println(i+"分钟");
                            try {
                                Thread.sleep((5*60*1000));
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                                System.err.println("Error-Thread.sleep 被打断");
                            }
                            i=i-5;
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                        System.err.println("Error-get请求到数据,存数据库时失败"+new Date().toString());
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static  String post(String url, Map<String,String> paramMap){
        CloseableHttpClient httpClient = HttpClients.createDefault();
            //创建httppost实例
            HttpPost httpPost = new HttpPost(url);
            //参数队列
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            Iterator iterator = paramMap.keySet().iterator();
            while (iterator.hasNext()){
                String key = (String) iterator.next();
                String value = paramMap.get(key);
                params.add(new BasicNameValuePair(key,value));
            }
        UrlEncodedFormEntity entity;
        try{
            //将参数设置在entity对象中
            entity = new UrlEncodedFormEntity(params,"UTF-8");
            //将entity对象设置httppost中
            httpPost.setEntity(entity);
            //执行请求，获得响应
            CloseableHttpResponse response = httpClient.execute(httpPost);
            try {
                //拿到响应实体
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity!=null){ // 处理返回的响应
                    System.out.println(EntityUtils.toString(responseEntity,"UTF-8")); //打印返回内容
                    String content = EntityUtils.toString(responseEntity,"UTF-8"); // 响应数据，存入数据库

                }
            }catch (Exception e){}finally {
                //关闭响应对象
                response.close();
            }
        }catch (Exception e){}finally {
            try {
                //关闭连接 ，释放资源
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    public static void main(String[] args){
    }
}
